<?php

namespace App\Http\Controllers;

use App\Export\DoneOrderExport;
use App\Http\Controllers\Api\ApiController;
use App\Models\OrderGoodsModel;
use App\Models\Refund\RefundSignTotalModel;
use App\Models\UserModel;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class DfController extends ApiController
{
    /**
     * 获取代发用户
     * @return JsonResponse
     */
    public function getDfUser(): JsonResponse
    {
        $userData = UserModel::where('role', 'daifa')->get(['id', 'username'])->toArray();
        return $this->success($userData);
    }

    /**
     * 分页获取拿货数据
     * @param Request $request
     * @return JsonResponse
     */
    public function getDoneOrderData(Request $request): JsonResponse
    {
        $date = $request->input('date') ?: Carbon::today()->toDateString();
        $uid = $request->input('uid', 0);
        $goodsSnPaginate = OrderGoodsModel::where('done_status', 1)->whereDate('doned_at', $date)->where('doned_uid', $uid)
            ->select('goods_sn')->distinct('goods_sn')->paginate(10);
        $items = json_decode(json_encode($goodsSnPaginate->items()), true);
        $list = $this->formatDoneOrderData($items, $date, $uid);
        return $this->success([
            'total'  => $goodsSnPaginate->total(),
            'page'   => $goodsSnPaginate->currentPage(),
            'limit'  => $goodsSnPaginate->perPage(),
            'pages'  => $goodsSnPaginate->lastPage(),
            'list'   => $list
        ]);
    }

    /**
     * 导出拿货数据
     * @param Request $request
     * @return BinaryFileResponse
     */
    public function doExportDoneOrderData(Request $request): BinaryFileResponse
    {
        $date = $request->input('date') ?: Carbon::today()->toDateString();
        $uid = $request->input('uid', 0);
        $items = OrderGoodsModel::where('done_status', 1)->whereDate('doned_at', $date)->where('doned_uid', $uid)
            ->select('goods_sn')->distinct('goods_sn')->orderByDesc('doned_at')->orderBy('sid')->get()->toArray();
        $list = $this->formatDoneOrderData($items, $date, $uid);
        return Excel::download(new DoneOrderExport($list), '拿货数据导出'.rand(1, 100).'.xlsx');
    }

    /**
     * 格式化拿货数据
     * @param $items
     * @param $date
     * @param $uid
     * @return array
     */
    private function formatDoneOrderData($items, $date, $uid): array
    {
        $list = [];
        if (!empty($items)) {
            $goodsSns = array_column($items, 'goods_sn');
            $goodsCollection = OrderGoodsModel::where('done_status', 1)->whereDate('doned_at', $date)
                ->where('doned_uid', $uid)->whereIn('goods_sn', $goodsSns)
                ->select('goods_id', 'goods_sn', 'goods_name', 'color', 'size', 'weight', 'price', 'goods_num', 'sid', 'sname', 'goods_remark')->get();
            $refundSignCollection = RefundSignTotalModel::where('date', $date)->where('doned_uid', $uid)->where('total', '<', 0)
                ->selectRaw('sid, SUM(total) as total')->groupBy('sid')->get();
            $supplyData = [];
            foreach ($refundSignCollection as $supplyTotal) {
                $supplyData[$supplyTotal->sid] = $supplyTotal->total;
            }
            foreach ($items as $item) {
                $goods = $goodsCollection->where('goods_sn', $item['goods_sn'])->first();
                if ($goods) {
                    $goods->goods_num = $goodsCollection->where('goods_sn', $item['goods_sn'])->sum('goods_num');
                    $goods->total = $goods->goods_num * $goods->price;
                    $goods->minus = $supplyData[$goods->sid] ?? 0;
                    $supplyData[$goods->sid] = 0;
                    $list[] = $goods;
                }
            }
        }
        return $list;
    }
}
